package androidApplication;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Random;

import capstone.aw_capstone_androidapplication.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Pairing extends Activity {
//	private int pairKey = "";
	private Button btnGeneratePairKey;
	private TextView txtPairKey;
	
	public Pairing(){
//		pairKey = "Test";
	}
	public void onCreate(Bundle b){
		super.onCreate(b);
		setContentView(R.layout.pairing);
		btnGeneratePairKey = (Button) findViewById(R.id.btnGeneratePairKey);
		btnGeneratePairKey.setOnClickListener(btnGeneratePairKeyClicked);
		
		Commons common = (Commons) getIntent().getSerializableExtra("Commons");
		ArrayList<String> config = common.getFileIO().getConfigFile();
		String pairKey = "";
		for(int i = 0; i < config.size(); i++){
			String s = config.get(i);
			String[] value = s.split(":");
			if(value[0].equals("rsaexp")){
				pairKey = value[1];
			}
		}
		txtPairKey = (TextView) findViewById(R.id.txtPairKey);
		txtPairKey.setText(pairKey);
	}
	
	private String generateKey(){	
		Random rand = new Random();
		BigInteger exp = BigInteger.valueOf((rand.nextInt(89999)+10000));
		
		return String.valueOf(exp);
	}
	
	private final Button.OnClickListener btnGeneratePairKeyClicked = new Button.OnClickListener(){
		@Override
		public void onClick(View v){
			String pairKey = generateKey();
			//update config here
			Commons common = (Commons) getIntent().getSerializableExtra("Commons");
			ArrayList<String> config = common.getFileIO().getConfigFile();
			for(int i = 0; i < config.size(); i++){
				String s = config.get(i);
				String[] value = s.split(":");
				if(value[0].equals("rsaexp")){
					String t = value[0] + ":" + pairKey;
					config.set(i, t);
					break;
				}
			}
			common.getFileIO().updateConfigFile(config);
			txtPairKey.setText(pairKey);
			System.out.println(pairKey + "Listener");
			
		}
	};	
}
